<!DOCTYPE HTML>
<html>
<head>

    <!--    <title>WEB表单设计器 Ueditor Formdesign Plugins -leipi.org</title>-->
    <!--    <meta name="keyword"-->
    <!--          content="ueditor Formdesign plugins,formdesigner,ueditor扩展,web表单设计器,高级表单设计器,Leipi Form Design,web form设计器,web form designer,javascript jquery ueditor php表单设计器,formbuilder">-->
    <!--    <meta name="description"-->
    <!--          content="Ueditor Web Formdesign Plugins 扩展即WEB表单设计器扩展，它通常在、OA系统、问卷调查系统、考试系统、等领域发挥着重要作用，你可以在此基础上任意修改使功能无限强大！">-->

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link href="css/bootstrap/css/bootstrap.css?2023" rel="stylesheet" type="text/css"/>
    <link href="css/site.css?2023" rel="stylesheet" type="text/css"/>

    <!--style>
        .list-group-item{padding:0px;}
    </style-->

    <style>
        .container {
            /*width: auto;*/
            /*padding: 20px;*/
        }
    </style>
    <!--    <script src="../../../static/vendor/layui/layer/layer.js"></script>-->
    <script type="text/javascript" charset="utf-8" src="js/jquery-1.7.2.min.js?2023"></script>
    <script src="../lib/jquery/fix.js"></script>
    <script type="text/javascript" charset="utf-8" src="js/ueditor/ueditor.config.js?2023"></script>
    <script type="text/javascript" charset="utf-8" src="js/ueditor/ueditor.all.js?2023"></script>
    <script type="text/javascript" charset="utf-8" src="js/ueditor/lang/zh-cn/zh-cn.js?2023"></script>
    <!--    <script type="text/javascript" charset="utf-8" src="js/ueditor/formdesign/leipi.formdesign.v4.js?2023"></script>-->
    <!--    <script src="../../../static/htmljs/utils.js"></script>-->
    <!--    <script src="../../../static/vendor/artTemplate/template-web.js"></script>-->
    <script src="../lib/layer/layer.js"></script>
    <script src="../lib/htmljs/md5.js"></script>
    <script src="../lib/vue/vue.js"></script>
    <script src="../lib/vue/vue-util.js"></script>
</head>
<body>

<div id="app" class="container" style="padding-top: 20px;">
    <form method="post" class="" id="saveform" name="saveform">
        <input type="hidden" name="_id" id="fields" :value="data._id">
        <div class="form-group">
            <label class="span2">表单名</label>
            <input type="text" class="span10 form-control" :value="data.name" name="name"/>
        </div>
        <div class="form-group">
            <label class="span2">表单说明</label>
            <textarea style="resize:vertical" type="text" class="span10 form-control" name="desc"
                      :value="data.desc || ''"></textarea>
        </div>

        <div class="row" style="position: relative">
            <div class="span2 toolbar" style="position:absolute; left: 20px; top:0">
                <ul class="nav nav-list" v-once>
                    <li class="nav-header">表单控件</li>
                    <li v-for="(v,i) in Object.assign(items, items_new)"><a href="javascript:void(0);" @click="exec(i)"
                                                                            class="btn btn-link">{{v}}</a></li>
                </ul>
            </div>

            <div class="span10" style="margin-left: 180px" ref="form">
            </div>

        </div><!--end row-->

        <div class="text-center" style="text-align: center; padding-top: 20px;">
            <a href="javascript:;" class="btn btn-primary save" style="padding-left: 20px;padding-right: 20px;" @click="save">保存</a>
        </div>

    </form>
</div><!--end container-->


<!-- script start-->
<script type="text/javascript">
    loadComponent("form-tmpl", "./template.html");

    UE.leipiFormDesignUrl = 'formdesign';

    //自带的旧控件，不相互纠缠到一起
    var createPlugin = function (name, title) {
        UE.plugins[name] = function () {
            var me = this, thePlugins = name;//'datetime';
            me.commands[thePlugins] = {
                execCommand: function () {
                    var dialog = new UE.ui.Dialog({
                        iframeUrl: this.options.UEDITOR_HOME_URL + UE.leipiFormDesignUrl + '/' + name + ".html",//'/datetime.html',
                        name: thePlugins,
                        editor: this,
                        title: title,
                        cssRules: "width:590px;height:370px;",
                        buttons: [
                            {
                                className: 'edui-okbutton',
                                label: '确定',
                                onclick: function () {
                                    dialog.close(true);
                                }
                            },
                            {
                                className: 'edui-cancelbutton',
                                label: '取消',
                                onclick: function () {
                                    dialog.close(false);
                                }
                            }]
                    });
                    dialog.render();
                    dialog.open();
                }
            };
        }
    };

    //新版控件可以用vue动态的使用
    var createPluginNew = function (name, title) {
        UE.plugins[name] = function () {
            var me = this, thePlugins = name;//'datetime';
            me.commands[thePlugins] = {
                execCommand: function () {
                    var dialog = new UE.ui.Dialog({
                        iframeUrl: this.options.UEDITOR_HOME_URL + UE.leipiFormDesignUrl + '/item.html?type=' + name,//'/datetime.html',
                        name: thePlugins,
                        editor: this,
                        title: title,
                        cssRules: "width:590px;height:370px;",
                        buttons: [
                            {
                                className: 'edui-okbutton',
                                label: '确定',
                                onclick: function () {
                                    dialog.close(true);
                                }
                            },
                            {
                                className: 'edui-cancelbutton',
                                label: '取消',
                                onclick: function () {
                                    dialog.close(false);
                                }
                            }]
                    });
                    dialog.render();
                    dialog.open();
                }
            };
        }
    }
    var leipiEditor;
    var app = new Vue({
        el: "#app",
        data: {
            id: "",
            pid: "",
            data: {},
            items: {
                text: "文本框",
                textarea: "多行文本",
                select: "下拉菜单",
                radios: "单选框",
                checkboxs: "复选框",
                macros: "宏控件",
                datetime: "日期控件",
                sign: "签名控件",
            },
            //从这里开始，是优化过的控件页面
            items_new: {
                chooseuser: "选人控件",
                choosedep: "选部门控件",
                chooseimage: "图片控件",
                annex: "附件控件",
                // comment: "批注控件"
            }
        },
        mounted() {
            this.id = getParam("id");
            this.pid = getParam("pid");

            //初始化控件
            for (var i in this.items) {
                createPlugin(i, this.items[i])
            }
            for (var i in this.items_new) {
                createPluginNew(i, this.items_new[i])
            }

            var form = this.$refs.form;
            var script;
            $(form).append(
                script = $("<script>")
                    .attr("type", "text/plain")
                    .attr("id", "myFormDesign")
                    .css("width", "100%")
            );

            if (this.id) {
                $.get("/api/bpm/form/one", {id: this.id}, (msg) => {
                    this.data = msg.data || {}
                    script.html((this.data.form && this.data.form.template) ? this.data.form.template : "");
                    init();
                }, "json");
            } else {
                init();
            }

            function init() {
                leipiEditor = UE.getEditor('myFormDesign', {
                    //allowDivTransToP: false,//阻止转换div 为p
                    toolleipi: true,//是否显示，设计器的 toolbars
                    textarea: 'design_content',
                    //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
                    toolbars: [[
                        'fullscreen', 'source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'removeformat', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', '|', 'fontfamily', 'fontsize', '|', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'link', 'unlink', '|', 'horizontal', 'spechars', 'wordimage', '|', 'inserttable', 'deletetable', 'mergecells', 'splittocells']],
                    //focus时自动清空初始化时的内容
                    //autoClearinitialContent:true,
                    //关闭字数统计
                    wordCount: false,
                    //关闭elementPath
                    elementPathEnabled: false,
                    //默认的编辑区域高度
                    initialFrameHeight: 500,
                    enableAutoSave: false

                    ///,iframeCssUrl:"css/bootstrap/css/bootstrap.css" //引入自身 css使编辑器兼容你网站css
                    //更多其他参数，请参考ueditor.config.js中的配置项
                });

                leipiFormDesign = {
                    /*执行控件*/
                    exec: function (method) {
                        leipiEditor.execCommand(method);
                    },
                    /*
                        Javascript 解析表单
                        template 表单设计器里的Html内容
                        fields 字段总数
                    */
                    parse_form: function (template, fields) {
                        var idex = $("[leipiplugins]").length;
                        var getAttrs = function (t) {
                            var ret = {};
                            $.each(t.attributes, function () {
                                // this.attributes is not a plain object, but an array
                                // of attribute nodes, which contain both the name and value
                                if (this.specified) {
                                    // if(this.name == 'name' && this.value == "leipiNewField"){
                                    //     this.value = "data_" + (++idex);
                                    // }
                                    ret[this.name] = this.value;
                                    // console.log(this.name, this.value);
                                }
                                //补充checkbox的默认值
                                if(ret['leipiplugins'] === 'checkboxs'){
                                    ret["checked"] = $(t).find(":checked").toArray()
                                        .map(e => e.value);
                                }
                            });
                            return ret;
                        }

                        var form = []
                        var box = $("<div>").append(template);
                        box.find("input[leipiplugins], span[leipiplugins], textarea[leipiplugins], img[leipiplugins],button[leipiplugins]").each(function () {
                            var t = $(this);
                            var type = t.attr("leipiplugins");
                            var data = null;
                            switch (type) {

                                case "select":
                                    var select = $(this).find("select");
                                    if (select.length) {
                                        var attrs = getAttrs(select[0])
                                        data = attrs;
                                        data.values = []
                                        data.defaultValue = select.val()
                                        $(this).find("option").each(function () {
                                            data.values.push($(this).val())
                                        });
                                        data.name = md5(data.title)
                                    }
                                    break

                                case "radios":
                                case "checkboxs":
                                    var items = $(this).find("input");
                                    if (items.length > 0) {
                                        data = getAttrs(this);
                                        data.values = [];
                                        items.each(function () {
                                            data.values.push($(this).val())
                                        });
                                        data.name = md5(data.title);
                                        // data.name = items[0].attr("name");
                                    }
                                    break;

                                default:
                                    var attrs = getAttrs(this)
                                    data = attrs;
                                    data.name = md5(data.title)
                                    break
                            }
                            if (data) {
                                form.push(data)
                                if (t.is("span")) {
                                    t.find("input,select").attr('name', data.name)
                                } else {
                                    t.attr("name", data.name);
                                }
                                // t.replaceWith("<span>{"+data.name+"}</span>")
                            }

                        });

                        console.log(box.html());

                        return {
                            template: box.html(),
                            // parse: box.html(),
                            data: form
                        }
                    },
                    /*type  =  save 保存设计 versions 保存版本  close关闭 */
                    fnCheckForm: function (type) {
                        if (leipiEditor.queryCommandState('source'))
                            leipiEditor.execCommand('source');//切换到编辑模式才提交，否则有bug

                        if (leipiEditor.hasContents()) {
                            leipiEditor.sync();/*同步内容*/

                            var data = {
                                id: $("[name=_id]").val(),
                                name: $("[name=name]").val(),
                                desc: $("[name=desc]").val(),
                                pid: app.pid
                                // content: leipiEditor.getContent(),
                            };
                            data.form = leipiFormDesign.parse_form(leipiEditor.getContent());

                            layer.load(0, {time: 5000})
                            $.ajax({
                                url: "/api/bpm/form/add",
                                type: "post",
                                headers: {
                                    "Content-Type": "application/json"
                                },
                                data: JSON.stringify(data),
                                dataType: "json",
                                success: function (msg) {
                                    layer.closeAll()
                                    if (!msg.success) {
                                        layer.msg(msg.errMessage)
                                        return
                                    }
                        if(typeof VApp !== 'undefined'){
                             (VApp.dispatch("FormDesign", "load", null, true));
                        } else {
                            layer.msg("保存成功");
                            localStorage.removeItem("form-saved");
                            localStorage.setItem("form-saved", 1);
                            top.closeCurrentTab && top.closeCurrentTab();
                        }
                                    // parent.onFormEdited(data.id ? "edit" : "add", msg.data);
                                    // console.log(msg);
                                    //
                                    // var id = (frameElement && frameElement.id);
                                    // if(id){
                                    //     top.$("a[data-iframe=" + id + "]").next("i").click()
                                    // }
                                }
                            });


                            // var data = {
                            //
                            // }
                            // console.log(leipiEditor.getContent())
                            // console.log(leipiFormDesign.parse_form(leipiEditor.getContent()))
                            //
                            // alert("你点击了保存,这里可以异步提交，请自行处理....");
                            return false;
                            //--------------以下仅参考-----------------------------------------------------------------------------------------------------
                            var type_value = '', formid = 0, fields = $("#fields").val(), formeditor = '';

                            if (typeof type !== 'undefined') {
                                type_value = type;
                            }
                            //获取表单设计器里的内容
                            formeditor = leipiEditor.getContent();
                            //解析表单设计器控件
                            var parse_form = this.parse_form(formeditor, fields);
                            //alert(parse_form);

                            //异步提交数据
                            $.ajax({
                                type: 'POST',
                                url: '/index.php?s=/index/parse.html',
                                //dataType : 'json',
                                data: {'type': type_value, 'formid': formid, 'parse_form': parse_form},
                                success: function (data) {
                                    if (confirm('查看js解析后，提交到服务器的数据，请临时允许弹窗')) {
                                        win_parse = window.open('', '', 'width=800,height=600');
                                        //这里临时查看，所以替换一下，实际情况下不需要替换
                                        data = data.replace(/<\/+textarea/, '&lt;textarea');
                                        win_parse.document.write('<textarea style="width:100%;height:100%">' + data + '</textarea>');
                                        win_parse.focus();
                                    }

                                    /*
                                  if(data.success==1){
                                      alert('保存成功');
                                      $('#submitbtn').button('reset');
                                  }else{
                                      alert('保存失败！');
                                  }*/
                                }
                            });

                        } else {
                            layer.msg('表单内容不能为空！')
                            // $('#submitbtn').button('reset');
                            return false;
                        }
                    },
                    /*预览表单*/
                    fnReview: function () {
                        if (leipiEditor.queryCommandState('source'))
                            leipiEditor.execCommand('source');/*切换到编辑模式才提交，否则部分浏览器有bug*/

                        if (leipiEditor.hasContents()) {
                            leipiEditor.sync();       /*同步内容*/


                            // alert("你点击了预览,请自行处理....");
                            // return false;
                            //--------------以下仅参考-------------------------------------------------------------------


                            /*设计form的target 然后提交至一个新的窗口进行预览*/
                            // document.saveform.target = "mywin";
                            // window.open('', 'mywin', "menubar=0,toolbar=0,status=0,resizable=1,left=0,top=0,scrollbars=1,width=" + (screen.availWidth - 10) + ",height=" + (screen.availHeight - 50) + "\"");
                            //
                            // document.saveform.action = "/index.php?s=/index/preview.html";
                            // document.saveform.submit(); //提交表单
                        } else {
                            alert('表单内容不能为空！');
                            return false;
                        }
                    }
                };

            }

            $(window).scroll(function () {
                var item = $(".toolbar");
                var reduce = $(window).scrollTop() - item.parent().offset().top;
                if (reduce > 0) {
                    item.css({
                        "position": "fixed",
                        left: item.parent().offset().left + 20
                    })
                } else {
                    item.css({
                        "position": "absolute",
                        left: 20
                    })
                }
            });
        },
        methods: {
            exec(i) {
                leipiFormDesign.exec(i);
            },
            save(){
                leipiFormDesign.fnCheckForm();
            }
        }
    });

    // var app = new Vue({
    //      el:"#app",
    //     data:{
    //         id: "",
    //         pid:"",
    //         data:{}
    //     },
    //     mounted(){
    //         this.id = getParam("id");
    //         this.pid = getParam("pid");
    //         $.get("/api/bpm/form/one", {id: this.id},  (msg) => {
    //             this.data = msg.data || {}
    //             // init();
    //         },"json");
    //     }
    // });


</script>
<!-- script end -->


</body>
</html>
